<template>
  <div>
    <el-dialog
      :visible.sync="visible"
      v-bind="$attrs"
      :close-on-click-modal="false"
      @close="closeCallback"
    >
      <el-form
        ref="elFormRef"
        :model="courseData.form"
        :rules="courseData.rules"
        label-width="auto"
      >
        <el-form-item prop="title" label="课程名称">
          <el-input v-model="courseData.form.title" placeholder="请输入课程名称" />
        </el-form-item>

        <el-form-item prop="day" label="学习周期（天）">
          <el-input v-model="courseData.form.day" type="number" maxlength="3"
          placeholder="请输入学习周期" />
        </el-form-item>

        <el-form-item prop="data" label="课程章节">
          <el-button type="text" @click="openAddSectionDialog">
            {{ sectionTextFormat }}
          </el-button>
        </el-form-item>

        <el-form-item prop="cover" label="课程封面">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :action="'/api/v1/upload/file'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            accept=".jpg,.jpeg,.png"
          >
            <img v-if="courseData.form.cover" :src="courseData.form.cover" class="avatar" alt="封面">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="showAddSectionDialog"
      title="章节信息"
      :close-on-click-modal="false"
    >
      <div style="margin-bottom: 20px;">
        <el-button type="primary" @click="openEnterSectionDialog">添加章节</el-button>
      </div>
      <el-table
        :data="sectionDataCopy"
        border
      >
        <el-table-column label="章节名称" prop="name" align="center" />
        <el-table-column label="操作" align="center">
          <template v-slot="{ row, $index }">
            <el-button type="primary" size="mini" @click="editSection(row, $index)">编辑</el-button>
            <el-button type="danger" size="mini" @click="removeSection($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer">
        <el-button @click="sectionInfoCancel">取消</el-button>
        <el-button type="primary" @click="sectionInfoConfirm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="showSection"
      :close-on-click-modal="false"
      size="35%"
    >
      <template #title>
        <div>添加章节</div>
      </template>

      <div style="padding: 0 20px;">
        <el-form
          ref="sectionFormRef"
          :model="sectionData"
          label-width="auto"
          :rules="sectionRules"
        >
          <el-form-item prop="name" label="章节名称：">
            <el-input v-model="sectionData.name" placeholder="请输入章节名称" />
          </el-form-item>
          <el-form-item prop="duration" label="学习视频：">
            <el-button type="text" @click="handleOpenVideoDialog">
              {{ formatterText }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="addSectionCancel">取消</el-button>
        <el-button type="primary" @click="addSectionConfirm">确定</el-button>
      </div>
    </el-dialog>

    <VideosDialog
      ref="videoDialogRef"
      v-model="showVideoDialog"
      :selected="sectionData.duration"
      @onConfirm="videoDialogConfirm"
    />
  </div>
</template>
<script>
import VideosDialog from '@/views/train/components/Course/videosDialog.vue'
import { cloneDeep } from 'lodash-es'
const durationValidator = (rule, value, callback) => {
  if (value.length <= 0) {
    callback(new Error('请添加至少一个学习视频'))
  } else {
    callback()
  }
}

const sectionValidator = (rule, value, callback) => {
  if (value.length <= 0) {
    callback(new Error('请添加至少一个章节'))
  } else {
    callback()
  }
}

const dayValidator=(rule, value, callback)=>{
  if (value<=0 || value>999) {
    callback(new Error('学习周期应在1-999之间'))
  } else {
    callback()
  }
}
export default {
  name: '',
  components: {
    VideosDialog
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    submitLoading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      courseData: {
        form: {
          title: '',
          cover: '',
          day: '',
          data: []
        },
        rules: {
          title: [
            { required: true, message: '请输入课程名称', trigger: ['blur', 'change'] },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
          ],
          day: [
            { required: true, message: '请输入课程学习周期', trigger: ['blur', 'change'] },
            { validator:dayValidator }
          ],
          cover: [{ required: true, message: '请上传课程封面', trigger: ['blur', 'change'] }],
          data: [{ required: true, validator: sectionValidator }]
        }
      },

      showAddSectionDialog: false,
      showVideoDialog: false,
      showSection: false,
      sectionData: {
        name: '',
        sort: null,
        duration: []
      },
      sectionDataCopy: [],
      sectionRules: {
        name: [{ required: true, message: '请输入章节名称', trigger: ['blur', 'change'] }],
        duration: [{ required: true, validator: durationValidator }]
      },
      currentIndex: null
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(e) {
        this.$emit('input', e)
      }
    },
    formatterText() {
      const len = this.sectionData.duration.length
      return len > 0 ? `已添加${len}条学习视频` : '添加学习视频'
    },
    sectionTextFormat() {
      const len = this.courseData.form.data.length
      return len > 0 ? `已添加${len}个章节` : '添加章节'
    }
  },
  created() {
  },
  methods: {

    resetFields() {
      this.courseData.form = this.$options.data().courseData.form
    },

    setDefaultSectionData(course) {
      course.day=course.day.toString()
      console.log(course,'course');
      this.courseData.form = course
    },

    openAddSectionDialog() {
      this.showAddSectionDialog = true
      this.sectionDataCopy = cloneDeep(this.courseData.form.data)
    },

    handleAvatarSuccess(e) {
      console.log('e --------->', e)
      const { data } = e
      this.courseData.form.cover = data.path
    },

    closeCallback() {
      this.resetFields()
      this.$refs.elFormRef.resetFields()
    },

    handleCancel() {
      this.$emit('input', false)
    },

    validate(ref) {
      return new Promise((resolve, reject) => {
        this.$refs[ref].validate(flag => {
          resolve(flag)
        })
      })
    },

    async handleConfirm() {
      console.log(this.courseData.form.day,'day');
      const flag = await this.validate('elFormRef')
      if (!flag) return
      this.$emit('onConfirm', this.courseData.form)
    },

    openEnterSectionDialog() {
      this.showSection = true
      this.$nextTick(() => {
        this.$refs.sectionFormRef.resetFields()
      })
    },

    handleOpenVideoDialog() {
      this.showVideoDialog = true
    },

    videoDialogConfirm(e) {
      this.sectionData.duration = e
      this.$refs.sectionFormRef.validateField('duration')
    },

    sectionReset() {
      this.sectionData = this.$options.data().sectionData
      this.currentIndex = null
    },

    addSectionCancel() {
      this.sectionReset()
      this.showSection = false
    },

    async addSectionConfirm() {
      const flag = await this.validate('sectionFormRef')
      if (!flag) return

      if (!this.currentIndex && this.currentIndex !== 0) {
        this.sectionDataCopy.push(this.sectionData)
      } else {
        this.$set(this.sectionDataCopy, this.currentIndex, this.sectionData)
      }

      this.sectionReset()
      this.showSection = false
    },

    editSection(row, index) {
      this.currentIndex = index
      this.sectionData = cloneDeep(row)
      this.showSection = true
    },

    removeSection(index) {
      this.sectionDataCopy.splice(index, 1)
    },

    sectionInfoReset() {
      this.sectionDataCopy = []
    },

    sectionInfoCancel() {
      this.sectionInfoReset()
      this.showAddSectionDialog = false
    },

    sectionInfoConfirm() {
      if (this.sectionDataCopy <= 0) return this.$message.error('请添加至少一个章节')
      this.courseData.form.data = this.sectionDataCopy.map((item, index) => {
        return {
          ...item,
          sort: index + 1
        }
      })
      this.sectionInfoReset()
      this.showAddSectionDialog = false
      this.$refs.elFormRef.validateField('data')
    }
  }
}
</script>
<style lang="scss" scoped>
:deep(.avatar-uploader) {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}

</style>
